import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"
import {getShoppingsApi} from "../../request/shoppingCar/getShoppinsApi.ts"
import { message } from "antd"

interface shopping{
    id:number,
    shoppingName:string,
    shoppingCount:number,
    book_public:string,
    book_price:number,
    book_profile:string,
    img_url:string
}

interface init{
    shoppings:shopping[],
    allPrice:number
}


const initialState:init={
    shoppings:[],
    allPrice:0
}

// 获取购物车数据，并计算总价
export const getShoppingsAsync:any = createAsyncThunk(
    "shoppingCar/getShoppingsAsync",
    async()=>{
        return await getShoppingsApi()
    }
)

const shoppingCarSlice = createSlice({
    name:"shoppingCar",
    initialState,
    reducers:{
        addCount:(state,action:any)=>{
            state.shoppings.map((item,indexed)=>{
                if(action.payload === item.id){
                    state.allPrice += item.book_price
                    return item.shoppingCount++
                }
            })
        },
        decrementCount:(state,action:any)=>{
            state.shoppings.map((item,indexedDB)=>{
                if(action.payload === item.id && item.shoppingCount>0){
                    state.allPrice -= item.book_price
                    return item.shoppingCount--
                }
            })
        },
        delShopping:(state,action:any)=>{
            let ind = 0
            state.shoppings.map((item,indexedDB)=>{
                if(action.payload === item.id){
                    ind = indexedDB
                    // 总价也要减掉
                    state.allPrice -= item.book_price*item.shoppingCount
                }
            })
            if(ind === 0){
                state.shoppings.splice(0,1)
            }else{
                state.shoppings.splice(ind,ind)
            }
            return
        }
    },
    extraReducers(build){
        build
        // fulfilled是说方法执行成功怎么样
        .addCase(getShoppingsAsync.fulfilled,(state,action)=>{
            state.shoppings = action.payload.shoppings
            // 计算总价
            if(state.shoppings!=null){
                state.allPrice = 0
                state.shoppings.map((item,index)=>{
                    state.allPrice += item.book_price*item.shoppingCount
                })
            }
        })
    }
})
export const {addCount,decrementCount,delShopping} = shoppingCarSlice.actions
const reducer = shoppingCarSlice.reducer
export default reducer